<template>
  <div>
    <!-- 头部按钮区 -->
    <div style="margin: 20px 0" class="btn_box">
      <!-- 创建 -->
      <el-button type="primary" @click="handleAdd">创建用户</el-button>
    </div>
    <!-- 列表区 -->
    <el-table :data="users" style="width: 100%;height:380px" border>
      <!--type="index" 获取索引值，从1开始； label 显示的标题; prop 数据字段名； width 列的宽度 -->
      <el-table-column type="index" label="序号" width="60"></el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="phone" label="电话"></el-table-column>
      <el-table-column prop="create_time" label="创建时间" :formatter="resetDate"></el-table-column>
      <el-table-column prop="role_id" label="所属角色" :formatter="formatRole"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row._id)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row._id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
      layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />

    <!-- 添加用户对话框 -->
    <el-dialog v-model="userFormVisible" title="添加用户" width="500px">
      <el-form :model="user" ref="userFormRef" label-width="100px" label-position="right" style="width: 400px"
        :rules="rules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="user.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="user.password"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="user.name"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role_id">
          <el-select v-model="user.role_id" placeholder="请点击选择">
            <el-option v-for="option in roleList" :key="option._id" :label="option.name"
              :value="option._id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="user.phone"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="user._id == null ? addData(userFormRef) : updateData(userFormRef)">
            确定
          </el-button>
          <el-button @click="userFormVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
/** 获取时间数据--创建|授权 */
import { formateDate } from "@/utils/dateUtils"
const resetDate = (row: any, colum: any, cellValue: number, index: number) => {
  return formateDate(cellValue)
}
/** 引入vue方法 */
import { reactive, ref, onMounted, nextTick } from "vue"

// 引入角色类型
import type { roleInfoData } from "@/api/role/type"
//引入角色库
import useRoleStore from "@/store/modules/role"
let roleStore = useRoleStore();

// 引入用户类型
import type { userInfoData } from "@/api/user/type"
// 引入用户库
import useUserStore from "@/store/modules/user"
let userStore = useUserStore();
// 定义用户列表
const users = ref<userInfoData[] | undefined>([])

// 表单验证
import { FormInstance, FormRules, ElMessageBox, ElMessage } from "element-plus";

// 定义角色列表动态存储变量
let roleList = ref<roleInfoData[] | undefined>([]);

// 修改用户
const handleEdit = (_id: string) => {
  handleAdd()
  userStore.getUserById(_id).then(response => {
    user.value = response
  })
}
// 修改确认
const updateData = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      userStore.updateUser((user.value as userInfoData)).then(response => {
        userFormVisible.value = false
        getUserList()
      })
    } else { }
  })
}
// 删除用户
const handleDelete = (_id: string) => {
  ElMessageBox.confirm(
    "确定要删除此条数据吗？",
    "Warning",
    {
      confirmButtonText: "OK",
      cancelButtonText: "Cancel",
      type: "warning"
    }
  ).then(() => {
    userStore.deleteUser(_id).then(response => {
      getUserList()
      ElMessage({
        type: "success",
        message: "删除成功"
      })
    })
  }).catch(()=>{})
}


/** 所属角色         单体信息  详细信息    row_id         索引 */
const formatRole = (row: any, colum: any, cellValue: number, index: number) => {
  // console.log(roleList.value[cellValue]);
  // !!!报错原因:roleList数据由API异步请求获取
  // @ts-ignore
  // return roleList.value[cellValue-1].name;
  let role = roleList?.value?.find((item) => item._id == cellValue) || {};
  return role.name;
}
// 获取角色列表
const getRoleList = () => {
  if (roleStore.roles?.length) {
    roleList.value = roleStore.roles
  } else {
    // 状态码判断-成功接收数据
    roleStore.roleList().then(() => {
      roleList.value = roleStore.roles
    })
  }
}


// 获取用户列表
const getUserList = () => {
  // 状态码判断-成功接收数据
  userStore.getUserList({ page: currentPage.value, size: pageSize.value }).then((response) => {
    console.log(userStore.users);

    users.value = userStore.users,
      total.value = (response?.total as number)
    totalPage.value = total.value / pageSize.value
  })
}

/** 分页部分 */
// 当前页
const currentPage = ref(1)
// 单页条数
const pageSize = ref(5)
// 总条数
const total = ref(0)
// 总页数
const totalPage = ref(1)
// 单页条数变动触发
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getUserList()

}
// 当前页变动触发
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getUserList()

}

/** 用户信息操作 */
// 用户名输入校验
const validateUserName = (rule: any, value: any, callback: any) => {
  // 去空格
  value = value.trim()
  // 取字符串长度
  const length = value && value.length
  const pwdReg = /[a-zA-Z0-9_]+$/
  if (value === "") {
    callback(new Error("请输入账号"))
  }
  else if (length < 4 || length > 12) {
    callback(new Error("长度在4到12个字符"))
  }
  else if (!pwdReg.test(value)) {
    callback(new Error("账号必须是英文、数字或下划线组成"))
  } else {
    callback()
  }
}
// 手机号输入校验
const validatePhone = (rule: any, value: any, callback: any) => {
  value = value.trim()
  const phoneReg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
  if (value === "") {
    callback(new Error('请输入手机号码'))
  }
  else if (!phoneReg.test(value)) {
    callback(new Error('请输入正确的手机号码'))
  }
  else {
    callback()
  }
}
// 定义新用户数据内容
const user = ref<userInfoData | undefined>({
  _id: null,
  username: '',
  password: '',
  name: '',
  phone: '',
  role_id: '',
})

//创建用户弹窗显示
const userFormVisible = ref(false)
// 创建用户表单获取
const userFormRef = ref<FormInstance>();
// 创建用户表单验证规则
const rules = reactive<FormRules>({
  username: [
    // 是否必填，验证规则，验证触发条件
    { required: true, validator: validateUserName, trigger: ['blur', 'change'] }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: "blur" },
    { min: 3, message: "密码长度需大于4位", trigger: "blur" }
  ],
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" }
  ],
  role_id: [
    { required: true, message: "请选择角色", trigger: "blur" }
  ],
  phone: [
    { required: true, validator: validatePhone, trigger: ['blur', 'change'] }
  ]
})

// 创建用户
const handleAdd = () => {
  user.value = {
    _id: null,
    username: '',
    password: '',
    name: '',
    phone: '',
    role_id: '',
  }
  // 添加-弹窗显示状态--true
  userFormVisible.value = true
  nextTick(() => {
    // 添加-弹窗状态重置{resetFields()重置表单所有字段}
    console.log(userFormRef.value);
    userFormRef.value.resetFields()
  })
}
// 添加表单确认
const addData = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      userStore.addUser((user.value as userInfoData)).then(
        response => {
          userFormVisible.value = false
          getUserList()
        }
      )
    } else {
      return false
    }
  })
}

// 页面加载后执行角色表获取函数
onMounted(() => {
  getUserList(),
    getRoleList()
})

</script>

<style></style>